package fi.pyppe.android.gps;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import fi.pyppe.android.gps.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

/**
 * UploadActivity.
 * 
 * @author Pyppe
 */
public class UploadActivity extends Activity implements Runnable {
  
  public static final String FILE_DESCRIPTION = "fi.pyppe.android.gps.UploadActivity.fileDescription";
  public static final String FILE_DATA = "fi.pyppe.android.gps.UploadActivity.file";
  public static final String UPLOAD_URL = "fi.pyppe.android.gps.UploadActivity.httpPostUrl";

  private ProgressDialog pd;
  private String postResultMessage;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.upload_progress);
    
    pd = ProgressDialog.show(this, "Uploading...", "", true, false);
    Thread thread = new Thread(this);
    thread.start();
  }
  
  public void run() {
    String description = (String) getIntent().getExtras().get(FILE_DESCRIPTION);
    File file = (File) getIntent().getExtras().get(FILE_DATA);
    String uploadUrl = (String) getIntent().getExtras().get(UPLOAD_URL);
    
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(uploadUrl);
    try {
      MultipartEntity entity = new MultipartEntity();
      entity.addPart("description", new StringBody(description));
      entity.addPart("data", new FileBody(file));
      httppost.setEntity(entity);
      // Execute HTTP Post Request
      HttpResponse httpResponse = httpclient.execute(httppost);
      if (httpResponse.getStatusLine().getStatusCode() != 200) {
        postResultMessage = "Invalid response code: " + httpResponse.getStatusLine().toString();
      } else {
        String responseContent = convertStreamToString(httpResponse.getEntity().getContent());
        postResultMessage = responseContent;
      }
      
      handler.sendEmptyMessage(0);
    } catch (Exception e) {
      postResultMessage = (e.getMessage() != null) ? e.getMessage() : "Error sending data!";
      handler.sendEmptyMessage(0);
      return;
    }
    
  }
  
  private String convertStreamToString(InputStream is) throws IOException {
    if (is != null) {
      StringBuilder sb = new StringBuilder();
      String line;

      try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        while ((line = reader.readLine()) != null) {
          sb.append(line).append("\n");
        }
      } finally {
        is.close();
      }
      return sb.toString();
    } else {
      return "";
    }
  }
  

  private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      AlertDialog alertDialog = new AlertDialog.Builder(UploadActivity.this).create();
      alertDialog.setTitle("Upload finished");
      if (postResultMessage != null) {
        alertDialog.setMessage(postResultMessage);
      }
      alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          setResult(RESULT_OK);
          finish();
        }
      });
      alertDialog.show();
      pd.dismiss();
    }
  };

}
